<template>
    <div>

        <el-card style="width: 100%;">

            <!--          商品信息    标题-->
            <div slot="header" class="clearfix">
                <span style="font-weight: bold;font-size: 18px">我的购物车</span>
                <el-button style="float: right;margin-right: 10px" type="danger" @click="deleteSelectProducts"> 删除选中
                </el-button>
                <el-button style="float: right;margin-right: 20px" type="primary" plain @click="toCategory">
                    去选购
                </el-button>

                <!-- 删除商品信息的弹窗 -->
                <el-dialog
                        title="提示"
                        :visible.sync="dialogVisible_deleteSelect"
                        width="30%">
                    <span>真的要删除选中的所有商品吗？</span>
                    <span slot="footer" class="dialog-footer">
                                    <el-button @click="dialogVisible_deleteSelect = false">取 消</el-button>
                                    <el-button type="danger" @click="handleDeleteProducts">确 定</el-button>
                                </span>
                </el-dialog>

            </div>


            <!--     商品信息列表    展示-->
            <template>
                <el-table
                        ref="tableRef"
                        height="380"
                        :header-cell-style="{fontSize: '14px','text-align':'center'}"
                        :cell-style="{'text-align':'center'}"
                        :data="carts"
                        @selection-change="handleSelectCodeForTicket"
                        stripe
                        style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column width="85" label="序号" type="index" align="center"></el-table-column>

                    <el-table-column label="图片" width="150px">
                        <template slot-scope="scope">
                            <el-avatar shape="square" :size="80" fit="fill" :src="scope.row.product.image"></el-avatar>
                        </template>
                    </el-table-column>

                    <el-table-column prop="product.name" label="商品名称" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="product.price" label="单价(元)" show-overflow-tooltip></el-table-column>

                    <el-table-column label="数量">
                        <template slot-scope="scope">
                            <el-input-number
                                    style="width: 110px"
                                    v-model="scope.row.quantity"
                                    @change="handleChange(scope.row)"
                                    :min="1" :max="10"
                                    size="mini"
                            ></el-input-number>
                        </template>
                    </el-table-column>

                    <el-table-column label="小计" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span style="font-size: 15px;color: #ff0024">￥{{ scope.row.total }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column label="操作">
                        <template slot-scope="scope">

                            <router-link style="margin: 0 10px"
                                         :to="{ path: '/productInfo/',  query: { id: scope.row.product.id } }">
                                <el-button icon="el-icon-search" circle></el-button>
                            </router-link>

                            <el-button type="danger" icon="el-icon-delete" circle
                                       @click="handleDeleteButton(scope.row)"></el-button>

                        </template>
                    </el-table-column>
                </el-table>
            </template>

            <el-pagination
                    style="float: right;margin: 20px 0"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page.sync="currentPage"
                    :page-sizes="pageSizes"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next"
                    background
                    :total="total">
            </el-pagination>
        </el-card>


        <el-card>
            <el-row :gutter="10">
                <el-col :span="12"><span>商品总价（不包含运费）：</span><span
                        style="font-size: 25px;color: #ff0024">￥{{ totalPrice }}</span></el-col>
                <el-col :span="12">
                    <el-button type="danger" @click="toCheckPage" size="medium" style="float: right">去结算</el-button>
                </el-col>
            </el-row>
        </el-card>
    </div>


</template>
<script>
import {defineComponent} from 'vue'

export default defineComponent({
    name: "MyCarts",
    data() {
        return {
            dialogVisible_deleteSelect: false,  // 选中删除按钮弹出框

            carts: [],       // 购物车
            cartId: '',          // 存储购物车id
            userId: '',            // 存储用户id
            ids: [],                 // 存储被选中商品的id
            products: [],              // 存储商品信息

            totalPrice: 0,          // 商品总价

            currentPage: 1,          // 当前页码
            pageSizes: [5, 10, 50, 100], // 每页显示条数
            pageSize: 5,             // 每页显示条数
            total: 0,                // 商品总数
        }
    },
    mounted() {

        // 获取用户ID
        let account = JSON.parse(localStorage.getItem('account'))
        this.userId = account.id

        // 加载购物车
        this.loadCarts()


    },
    methods: {

        toCheckPage() {
            if (this.ids.length === 0) {
                this.$message.info('请选择商品')
                return
            }
            // 跳转到结算页面
            this.$router.push({name: 'checkoutPage', params: {num: this.ids}})
        },

        // 加载购物车
        loadCarts() {
            // 如果用户ID不存在则跳转登录
            if (!this.userId) {
                this.$router.push('/login');
            }
            this.$request.post('/cart/getCarts' + '?currentPage=' + this.currentPage
                + '&pageSize=' + this.pageSize
                + '&userId=' + this.userId).then(res => {
                if (res.code === '200') {
                    this.carts = res.data.list
                    this.total = res.data.total
                    // console.log(this.carts)
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

        // 加载商品信息
        loadProducts() {
            this.$request.post('/product/getProducts' + '?currentPage=' + this.currentPage
                + '&pageSize=' + this.pageSize
                + '&userId=' + this.userId).then(res => {
                if (res.code === '200') {

                }
            })
        },


        handleChange(value) {
            console.log(value);
            if (!value) {
                return
            }
            // 更新cart的数量和总价
            // 获取商品单价
            let price = value.product.price
            let quantity = value.quantity
            let total = value.quantity * price
            this.$request.post('/cart/updateCartNumAndTotalPrice' + '?id=' + value.id + '&quantity=' + quantity + '&total=' + total).then(res => {
                if (res.code === '200') {
                    this.loadCarts()
                }
            })
        },

        toCategory() {
            this.$router.push('/category')
        },


// 处理价格格式
        handlePriceFormat() {
            this.add_product.price = parseFloat(this.add_product.price).toFixed(2)
        },


// 删除选中二次确认
        handleDeleteProducts() {
            this.dialogVisible_deleteSelect = false;
            if (this.ids.length > 0) {
                // 删除选中
                this.$request.post('/cart/deleteByIds', this.ids).then(res => {
                    if (res.code === '200') {
                        this.$message.success('删除成功');
                        // 刷新数据
                        this.loadCarts()
                    } else {
                        this.$message.error(res.msg);
                    }
                })
            } else {
                this.$message.info('请选择要删除的商品');
            }
        },

// 删除选中二次提醒
        deleteSelectProducts() {
            // 显示二次提醒弹窗
            this.dialogVisible_deleteSelect = true;
        },

// 获取选中的商品id，
// 并存储到 ids 数组中
        handleSelectCodeForTicket(val) {
            let multipleSelection = val
            this.ids = val.map((item) => item.id);
            // 累加总价
            this.totalPrice = 0
            for (let i = 0; i < multipleSelection.length; i++) {
                this.totalPrice += multipleSelection[i].total
            }
            this.totalPrice = parseFloat(this.totalPrice).toFixed(2)
        },


// currentPage 改变时会触发
        handleCurrentChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.currentPage = val;

            // 发送请求获取相应数量的数据
            this.loadCarts()
        },


//  pageSize 改变时会触发
        handleSizeChange(val) {
            // 获取  当前页 和 页面大小  currentPage、pageSize
            this.pageSize = val;
            this.currentPage = 1;

            // 发送请求获取相应数量的数据
            this.loadCarts()
        },

        handleDeleteButton(cart) {
            if (!cart.id) {
                return;
            }
            this.$request.post('/cart/deleteById' + '?id=' + cart.id).then((res) => {
                if (res.code === '200') {
                    this.loadCarts()
                } else {
                    this.$message.error(res.msg);
                }
            })
        },

    }
})
</script>


<style scoped>


.el-dialog__body {
    padding: 10px 30px;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

input[type="number"] {
    -moz-appearance: textfield;
}


</style>